import json
from datetime import datetime
# 导入 Django 的时区工具
from django.utils import timezone
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from jewelry.models import UserInfo


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = 'chat_room'
        self.user = None

        await self.accept()

    async def receive(self, text_data):
        data = json.loads(text_data)
        action = data.get('action')

        if action == 'auth':
            # 用户认证
            self.user = await self.authenticate_user(data['token'])
            if self.user:
                await self.channel_layer.group_add(
                    self.room_name,
                    self.channel_name
                )
                await self.send_user_list()
        elif action == 'message':
            # 处理消息
            await self.handle_message(data)

    async def handle_message(self, data):
        receiver_id = data['receiver']
        message = {
            'type': 'chat_message',
            'sender': {
                'nickname': self.user.nickname,
                'avatar': self.user.avatar,
                'id': self.user.openid
            },
            'message': data['message'],
            'timestamp': str(timezone.now())
        }
        await self.channel_layer.group_send(
            self.room_name,
            {
                'type': 'send.message',
                'message': message,
                'receiver_id': receiver_id
            }
        )

    async def send_message(self, event):
        if event['receiver_id'] == self.user.openid:
            await self.send(text_data=json.dumps(event['message']))

    @database_sync_to_async
    def authenticate_user(self, token):
        # 这里需要实现实际的认证逻辑，比如验证微信登录态
        # 伪代码示例：
        user = UserInfo.objects.get(openid=token)
        return user

    async def send_user_list(self):
        users = await self.get_online_users()
        await self.send(text_data=json.dumps({
            'type': 'user_list',
            'users': users
        }))

    @database_sync_to_async
    def get_online_users(self):
        return list(UserInfo.objects.filter(
            last_online__gte=timezone.now() - timezone.timedelta(minutes=5)
        ).values('openid', 'nickname', 'avatar'))
